package com.gitee.feizns.quickstart.web.ex.impl;

import com.gitee.feizns.quickstart.domain.vo.Ret;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;

/**
 * POST请求体的内容仅通过 HttpMessage 没办法读取的的情况
 * @see HttpMessageNotReadableException
 * @author feizns
 * @since 2019/7/7
 */
@NoArgsConstructor
public class HttpMessageNotReadableExceptionHandler extends AbstractExceptionHandler<HttpMessageNotReadableException> {

    /**
     * 没有请求体信息的错误信息
     */
    private static final String MSG = "Required request body is missing";

    /**
     * 响应的Http状态
     */
    private HttpStatus httpStatus = HttpStatus.BAD_REQUEST;

    public HttpMessageNotReadableExceptionHandler(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }

    @Override
    public ResponseEntity<Ret<?>> handle(HttpMessageNotReadableException e) {
        String message = e.getMessage();
        if ( message != null && message.startsWith(MSG) )
            message = MSG;;
        return ResponseEntity.status(httpStatus)
                .body(Ret.error(HttpStatus.BAD_REQUEST.value(), message));
    }

}
